package integral

import (
	"context"
	"fmt"
	"github.com/samber/lo"
	"github.com/shopspring/decimal"
	"private-domain-overseas-service/admin/business/api/internal/repository/integral"
	"private-domain-overseas-service/pkg/constant"
	"private-domain-overseas-service/pkg/xerr"
	"private-domain-overseas-service/tools/ent"
	"time"

	"private-domain-overseas-service/admin/business/api/internal/svc"
	"private-domain-overseas-service/admin/business/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type IntegralGoodsListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 积分商城商品列表
func NewIntegralGoodsListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *IntegralGoodsListLogic {
	return &IntegralGoodsListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *IntegralGoodsListLogic) IntegralGoodsList(req *types.IntegralGoodsListRequest) (resp *types.IntegralGoodsListResponse, err error) {
	goodsDao := integral.NewIntegralGoodsDao(l.ctx, l.svcCtx)

	//定义换算单位变量
	baiDecimal := decimal.NewFromInt(100)

	//分页查询数据
	goodsInfos, total, err := goodsDao.IntegralGoodsConditionsPageAll(req.Current, req.PageSize)
	if err != nil {
		l.Logger.Infof("查询积分商品列表失败：%s", err.Error())
		return nil, xerr.ErrCodeMsg(xerr.ServerDbError, err.Error())
	}

	//返回组装数据
	list := lo.Map(goodsInfos, func(item *ent.HzIntegralGoods, _ int) *types.IntegralGoodsListInfo {
		return &types.IntegralGoodsListInfo{
			Id:              int64(item.ID),
			GoodsInfo:       item.GoodsInfo,
			GoodsImage:      fmt.Sprintf("%s%s", constant.IntegralGoodsImage, item.GoodsImage),
			GoodsSmallImage: fmt.Sprintf("%s%s", constant.IntegralGoodsImage, item.GoodsSmallImage),
			GoodsPrice:      decimal.NewFromInt(item.GoodsPrice).Div(baiDecimal).StringFixed(2),
			Sort:            item.GoodsSort,
			Status:          item.GoodsStatus,
			CreatedAt:       time.Unix(item.CreatedAt, 0).Format(time.DateTime),
			UpdatedAt:       time.Unix(item.UpdateAt, 0).Format(time.DateTime),
		}
	})

	//返回响应参数
	resp = &types.IntegralGoodsListResponse{
		List: list,
		Page: &types.PageResponse{
			Total:           total,
			PageSize:        req.PageSize,
			RequestPageSize: req.PageSize,
			Current:         req.Current,
		},
	}
	return resp, nil
}
